# -*- coding: utf-8 -*-
"""
Created on Thu Sep 16 16:55:08 2021

@author: chibi
"""
from PIL import Image, ImageDraw , ImageFont
import socket

import time 

esp_ip  = '192.168.88.100'
esp_port = 8888

serverAddressPort   = (esp_ip, esp_port)
bufferSize          = 1024
UDPClientSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)

def readimg(im):
    dim = (128, 64)
  
    # resize image
    im.thumbnail(dim, Image.ANTIALIAS)
    #im.show()
    im = im.convert("L")
    #im = im.convert("1")
    text =''
    point = 0
    for y in range (64):
        for x in range (128):
            if im.getpixel((x,y)) <50:
                get_point = 0
            else:
                get_point = 1
                
            
            now = int( get_point )<<(3-x%4) 
            #位数1/0 转二进制
           
            point += now
            
            if (x%4 ==3):
                text += hex(point)[2:]
               
                #text += "|"
                point = 0 #还原
    text += "#"
    #print(text)
    
    UDPClientSocket.sendto(text.encode('utf-8'), serverAddressPort)

w,h = 128,64


font = ImageFont.truetype(r'simhei.ttf',int(h*0.3))# 前面是字体路径 后面是字体大小
for  i in range(10):
    bg_img = Image.new('L',(w,h)) #新建一个图黑色背景
    if i%3 == 1:
        draw = ImageDraw.Draw(bg_img) 
         
        text = '我是John\n感谢大家收看'
        draw.text((0, 0), text, font = font ,fill='white')
        
        #bg_img.show()
        
        readimg(bg_img)
        time.sleep(1)
    else:
        draw = ImageDraw.Draw(bg_img) 
         
        text = '我是OLED\n!!!@@@!!'
        draw.text((0, 0), text, font = font ,fill='white')
        
        #bg_img.show()
        
        readimg(bg_img)
        time.sleep(1)
    